package com.securities.stock.dao;

import com.alibaba.fastjson.JSON;
import com.securities.stock.dto.CountCandleToolDto;
import com.securities.stock.dto.MaDto;
import com.securities.stock.job.CrawlerJob;
import com.securities.stock.mapper.CandleMapper;
import com.securities.stock.mapper.CandleViewMapper;
import com.securities.stock.pojo.Candle;
import com.securities.stock.pojo.CandleView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

@Service
public class CandleViewDao {


    private final static Logger LOGGER = LoggerFactory.getLogger(CrawlerJob.class);


    @Autowired
    private CandleViewMapper candleViewMapper;

    private  static  final  int DIVIDE_SCALE=8;
    /***
     * 一天交易日的时间换算成分钟
     */
    private  static  final  int TRANSACTION_MINUTE_DAY=4*60;


    @Autowired
    private CandleMapper candleMapper;


    public   List<CandleView> queryAnalysisByStockId(Long stockId){
        return candleViewMapper.selectAnalysisByStockId(stockId);
    }

    /****
     * 分析当条 CandleView
     * @param view
     */
    public void analysisCandleView(CandleView view){
        //分析均线点 3-60
        List<Candle> candles= candleMapper.queryClosingPrice(view.getStockId());
        CandleView analysisView=new CandleView();
        analysisView.setId(view.getId());
        analysisView.setStockId(view.getStockId());
        if(!CollectionUtils.isEmpty(candles)){
            BigDecimal closingPriceTotal=BigDecimal.ZERO;
            List<MaDto> maJson=new ArrayList<>();
            for(int i=0;i<candles.size();i++){
                closingPriceTotal=closingPriceTotal.add(candles.get(i).getCurrentPrice());
                if(i>1){
                    int maName=i+1;
                    BigDecimal maValue=closingPriceTotal.divide(new BigDecimal(maName),DIVIDE_SCALE,
                            RoundingMode.UP).setScale(4, RoundingMode.UP);
                    if(maName%3==0) {
                        maJson.add(new MaDto("ma" + maName, maValue));
                    }
                    if(maName==5){
                        analysisView.setMa5(maValue);
                    }
                    if(maName==10){
                        analysisView.setMa10(maValue);
                    }
                    if(maName==20){
                        analysisView.setMa20(maValue);
                    }
                    if(maName==30){
                        analysisView.setMa30(maValue);
                    }
                    if(maName==60){
                        analysisView.setMa60(maValue);
                    }
                }
            }
            analysisView.setMaJson(JSON.toJSONString(maJson));
        }
        //120均线点
        int days=120;
        Candle countCandleParam=new Candle();
        countCandleParam.setStockId(analysisView.getStockId());
        Long countCandle=candleMapper.selectCount(countCandleParam);
        if(countCandle>=days){
            //计算120并均值
            CountCandleToolDto countCandleToolDto=new CountCandleToolDto("current_price",analysisView.getStockId(),days);
            List<BigDecimal> closing120= candleMapper.queryColumnByDays(countCandleToolDto);
            BigDecimal closing120Total=BigDecimal.ZERO;
            for(BigDecimal closing:closing120){
                closing120Total=closing120Total.add(closing);
            }
            BigDecimal ma120Value=closing120Total.divide(new BigDecimal(days),DIVIDE_SCALE,
                    RoundingMode.UP).setScale(4, RoundingMode.UP);
            analysisView.setMa120(ma120Value);

        }
        //成交量的均线 3到30
        List<Candle> transactionNums= candleMapper.queryTransactionNum(view.getStockId());
        if(!CollectionUtils.isEmpty(transactionNums)){
            Long transactionNumTotal=0L;
            List<MaDto> transactionNumMaJson=new ArrayList<>();
            for(int i=0;i<transactionNums.size();i++){
                Candle transaction=transactionNums.get(i);
                transactionNumTotal=transactionNumTotal+transaction.getTransactionNum();
                if(i>1) {
                    int maName = i + 1;
                    BigDecimal maValue=new BigDecimal(transactionNumTotal).divide(new BigDecimal(maName),DIVIDE_SCALE,
                            RoundingMode.UP).setScale(4, RoundingMode.UP);
                    if(maName==5){
                        analysisView.setTransactionMa5(maValue);
                    }
                    if(maName==10){
                        analysisView.setTransactionMa10(maValue);
                    }
                    if(maName==3){
                        transactionNumMaJson.add(new MaDto("transactionMa" + maName, maValue));
                    }
                    if(maName%2==0) {
                        transactionNumMaJson.add(new MaDto("transactionMa" + maName, maValue));
                    }
                }
                analysisView.setTransactionMaJson(JSON.toJSONString(transactionNumMaJson));
            }
        }
        //量比
        int numDay=6;
        //量比＝现成交总手/（过去5日平均每分钟成交量×当日累计开市时间（分）
        if(countCandle>=numDay){
            CountCandleToolDto countCandleToolDto=new CountCandleToolDto("transaction_num",analysisView.getStockId(),numDay);
            List<BigDecimal> transactionNum6= candleMapper.queryColumnByDays(countCandleToolDto);
            //当日成交量
            BigDecimal todayTnum= transactionNum6.get(0);
            BigDecimal todayTnumRate= todayTnum.divide(new BigDecimal(TRANSACTION_MINUTE_DAY),DIVIDE_SCALE,
                    RoundingMode.UP);
            //过去五天的成交量
            BigDecimal days5Tnum=BigDecimal.ZERO;
            for(int i=1;i<numDay;i++){
                days5Tnum=days5Tnum.add(transactionNum6.get(i));
            }

            BigDecimal day5TnumRate=days5Tnum.divide(new BigDecimal(TRANSACTION_MINUTE_DAY*5),DIVIDE_SCALE,
                    RoundingMode.UP);
            if(BigDecimal.ZERO.compareTo(day5TnumRate)!=0) {
                BigDecimal numRate = todayTnumRate.divide(day5TnumRate, DIVIDE_SCALE,
                        RoundingMode.UP).setScale(4, RoundingMode.UP);
                analysisView.setNumRate(numRate);
            }
        }
        candleViewMapper.updateByPrimaryKeySelective(analysisView);
        LOGGER.info("[viewId={},stockId={}]分析完毕[ data={} ]",analysisView.getId(),analysisView.getStockId(),JSON.toJSONString(analysisView));
    }


}
